#!/usr/bin/env bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

#install jq
function install_jq() {
    get_linux_type
    
	yum install git -y
	cd $base_folder
	git clone ${jq_down_link}

	
	if [[ ${bit} = "x86_64" ]]; then
		mv $jq_folder/jq-linux64 ${jq_file}
	else
		mv $jq_folder/jq-linux32 ${jq_file}
	fi

	chmod +x ${jq_file}
	[[ ! -e ${jq_file} ]] && echo -e "${Error} ${Red_font_prefix}JQ解析器$({jq_file}) 剪切失败，请检查 ! ${Font_color_suffix}" && exit 1
	[[ -e ${jq_file} ]] && echo -e "${Info}${Green_font_prefix}JQ解析器剪切成功！${Font_color_suffix}"

}


# Getting configuration information of webdav 
function get_webdav_config(){
	echo -e "${Info} ${full_line}读取WebDAV配置信息中...${full_line}" && echo
	
	if [[ ! -e ${jq_file} ]]; then
		install_jq
	fi
	
	#get config info
	CommonName_from_jq=$(${jq_file} '.CommonName' ${webdav_config_file} | sed 's/^.//;s/.$//')
	webdav_go_https_port_from_jq=$(${jq_file} '.webdav_go_https_port' ${webdav_config_file} | sed 's/^.//;s/.$//')
	
	webdav_user_from_jq=$(${jq_file} '.webdav_user' ${webdav_config_file} | sed 's/^.//;s/.$//')
	webdav_pwd_from_jq=$(${jq_file} '.webdav_pwd' ${webdav_config_file} | sed 's/^.//;s/.$//')
	
	echo -e "${Info} ${full_line}读取WebDAV配置信息 END${full_line}" && echo
}








# 1.下载资源
function download_resources(){
	echo -e "${Info} ${full_line} 资源下载 start...${full_line}" && echo
	
	#下载 webdav-go
	cd $base_folder
	yum install git -y
	
	cd ${webdav_go_folder}/webdav-go
	chmod +x ${webdav_go_bin}
	
	# git clone ${webdav_go_download}
	
	#下载jq
	install_jq
	
	echo -e "${Info} ${full_line} 资源下载 END ${full_line}" && echo
}



# 2.生成自签名证书(见certficate/generateCert.sh  generate_self_cert)



# 3.配置webdav-go https的端口
function set_webdav_go_https_port(){
	while true
	do
		read -e -p "设置 webdav-go的https是协议端口(默认443端口，不要设置为80端口)" webdav_go_https_port
		if [[ -z ${webdav_go_https_port} ]]; then
			webdav_go_https_port=${default_webdav_go_https_port}
			echo &&  echo -e "webdav-go的https端口 : ${Green_font_prefix}${webdav_go_https_port}${Font_color_suffix}" && echo ${full_line} && echo
			
			break
			
		else
			echo -e "设置的端口：${Green_font_prefix}${webdav_go_https_port}${Font_color_suffix}"
		fi
		
		#使用expr命令检查输入的值是否为整数，如果输入的不为整数，命令返回值$？不为0
		expr $webdav_go_https_port + 1 &>/dev/null
		if [[ $? != 0 ]]; then
			echo -e "${Error} ${Red_font_prefix}输入的不是纯数字(1-65535)${Font_color_suffix}"
			read -p "按回车键重新设置" && echo
			continue
		fi

		#判断输入的数字是否以0开头  
		if [[ `expr index  ${webdav_go_https_port} 0` == 1 ]];then
			echo -e "${Error} ${Red_font_prefix}不要以0开头${Font_color_suffix}"
			read -p "按回车键重新设置" && echo
			continue
		fi
		
		
		if [[ $? == 0 ]]; then
			#ge >=   le <=  判断是否在范围1-65535内
			if [[ ${webdav_go_https_port} -ge 1 ]] && [[ ${webdav_go_https_port} -le 65535 ]]; then
				
				if [[ ${webdav_go_https_port} -eq 80 ]]; then
					echo -e "${Error} ${Red_font_prefix}http端口不要设置为80${Font_color_suffix}"
					continue
				else
					echo && echo ${full_line} && echo -e "webdav-go的https端口 : ${Green_font_prefix}${webdav_go_https_port}${Font_color_suffix}" && echo ${full_line} && echo
					break
				fi
			else
				echo -e "${Error} ${Red_font_prefix}输入的数字不在范围内(1-65535)${Font_color_suffix}"
				read -p "按回车键重新设置" && echo
			fi
		
		else
			echo -e "${Error} ${Red_font_prefix} 执行 set_nginx_port 系统异常！${Font_color_suffix}" & break
		fi
	done
}


# 4.生成随机用户名和密码（passwd\generatePasswd.sh  generate_random_user_and_pwd）
	






# 5.设置同步目录属性
function set_sync_folder(){
	echo -e "${Info} ${full_line} 设置同步目录属性 start... ${full_line}" && echo
	
	# 所属用户和用户组
	# 设置文件所有者 如果是所有人都可以使用的话设置  nobody:nobody
	chown root:root  $sync_folder
	#权限设置
	chmod -R 700 $sync_folder
	
	echo -e "${Info} ${full_line} 设置同步目录属性 END ${full_line}" && echo
	
}


# 6.写入WebDAV配置信息
function write_webdav_config(){
	echo -e "${Info} ${full_line}写入WebDAV配置信息 start... ${full_line}" && echo

	cat >${webdav_config_file} <<-EOF
{
"CommonName": "${CommonName}",
"webdav_go_https_port": "${webdav_go_https_port}",
"webdav_user": "${webdav_user}",
"webdav_pwd": "${webdav_pwd}",
"other": "other"
}
	EOF
	[[ ! -e $webdav_config_file ]] && echo -e "${Error}：配置信息写入失败" && break
	echo -e "${Info} ${full_line}写入WebDAV配置信息 END ${full_line}" && echo



}



# 7.生成 webdav-go 配置文件
function set_webdav_go_yml_file(){
echo -e "${Info} ${full_line} 生成 webdav-go 配置文件 start...${full_line}" && echo
	
cat >${webdav_go_yml} <<-EOF
# 服务器配置
# 允许访问的IP
address: 0.0.0.0
port: ${webdav_go_https_port}
# 开启认证
auth: true
## 使用https
tls: true


## 证书和私钥
cert: ${webdav_go_cert_folder}/server.crt 
key: ${webdav_go_cert_folder}/server.key


# prefix: 
# debug: false



# 默认用户设置(will be merged)
scope: .
modify: true
rules: []


# 跨域配置
# cors:
  # enabled: true
  # credentials: true
  # allowed_headers:
    # - Depth
  # allowed_hosts:
    # - http://localhost:8080
  # allowed_methods:
    # - GET
  # exposed_headers:
    # - Content-Length
    # - Content-Range
    

# scope为同步目录
users:
  - username: ${webdav_user}
    password: ${webdav_pwd}
    scope: ${sync_folder}
  # - username: encrypted
    # password: "{bcrypt}$2y$10$zEP6oofmXFeHaeMfBNLnP.DO8m.H.Mwhd24/TOX2MWLxAExXi4qgi"
  # - username: "{env}ENV_USERNAME"
    # password: "{env}ENV_PASSWORD"
  - username: basic
    password: basic
    modify:   false
    rules:
      - regex: false
        allow: false
        # path: 
      # - path: /public/access/
        modify: true
        
       

	EOF
	echo -e "${Info} ${full_line} 生成 webdav-go 配置文件 END ${full_line}" && echo
}




# 10.显示WebDAV配置信息
function display_webdav_config(){
	get_webdav_config

	#ouput config info
	if [[ ${webdav_go_https_port_from_jq} -eq 443 ]]; then
		echo && echo "==================================================="
		echo -e " WebDAV配置信息：" && echo
		echo -e " WebDAV URL\t    : ${Green_font_prefix}https://${CommonName_from_jq}${Font_color_suffix}"
		echo -e " WebDAV用户名\t    : ${Green_font_prefix}${webdav_user_from_jq}${Font_color_suffix}"
		echo -e " WebDAV密码\t    : ${Green_font_prefix}${webdav_pwd_from_jq}${Font_color_suffix}" && echo

		echo && echo "==================================================="
	else
		echo && echo "==================================================="
		echo -e " WebDAV配置信息：" && echo
		echo -e " WebDAV URL\t    : ${Green_font_prefix}https://${CommonName_from_jq}:${webdav_go_https_port_from_jq}${Font_color_suffix}"
		echo -e " WebDAV用户名\t    : ${Green_font_prefix}${webdav_user_from_jq}${Font_color_suffix}"
		echo -e " WebDAV密码\t    : ${Green_font_prefix}${webdav_pwd_from_jq}${Font_color_suffix}" && echo

		echo && echo "==================================================="
	fi
	

}



# -------------------------------webdav-go启动相关 -------------------------------

function check_webdav_go_status(){
	#webdav-go进程号
	webdav_go_pids=$(ps -ef | grep -v "grep" | grep "webdav-go" | awk '{print $2}')
	echo " webdav-go进程号：${webdav_go_pids}"
}


function stop_webdav_go(){


	kill -9  $(ps -ef|grep -v grep |grep "webdav-go" |awk  '{print $2}')
	

}



function start_webdav_go(){

	
	
	check_webdav_go_status
	
	if [[ ! -z ${webdav_go_pids} ]]; then
		echo -e "${Green_font_prefix}[信息]${Font_color_suffix} webdav-go 已经启动，无需再启动" && echo
		
	else
		
		echo -e "${Info_font_prefix}[信息]${Font_color_suffix}  开启 webdav-go  中..." && echo 
		echo -e "nohup ${webdav_go_bin} -c ${webdav_go_yml} > ${webdav_go_log} 2>&1 &"
		nohup ${webdav_go_bin} -c ${webdav_go_yml} > ${webdav_go_log} 2>&1 & 
			
		 
		check_webdav_go_status
		if [[ -z ${webdav_go_pids} ]]; then
			echo -e "${Error}${Red_font_prefix}启动失败，请手动启动（或者通过日志查找错误）${Font_color_suffix}  " && echo
		else	
			echo -e "${Green_font_prefix} 启动成功！${Font_color_suffix} " && echo
		fi
	fi
	

}


function restart_webdav_go(){
	echo -e "${Info} ${full_line} webdav-go 重启中... ${full_line}" && echo
	check_webdav_go_status
	if [[ -z ${webdav_go_pids} ]]; then
		# 当前处于关闭状态
		start_webdav_go
	else
		# 当前处于开启状态
		stop_webdav_go && start_webdav_go
	fi
	
	

}


# -------------------------------webdav-go启动相关 -------------------------------





# ------------------------------------------------------------------------------------------
function check_webdavGo_install_status(){
	if [[ ! -e "${webdav_go_bin}" ]] || [[ ! -e "${webdav_config_file}" ]]; then
		echo -e " webdav-go状态：${Red_font_prefix} 未安装 ${Font_color_suffix}"
	
	else
		check_webdav_go_status
		if [[ -z ${webdav_go_pids} ]]; then
			echo -e " webdav-go状态： 已安装但${Red_font_prefix}未启动 ${Font_color_suffix}"
		else
			echo -e " webdav-go状态： ${Green_font_prefix}已经启动 ${Font_color_suffix}"
		fi
	fi
	


}


function auto_install_and_start_webdavGo(){
	# 1.下载资源
	download_resources
	
	# 2.生成自签名证书(generateCert.sh)
	generate_self_cert
	
	# 3.配置webdav-go https的端口
	set_webdav_go_https_port
	
	# 4.生成随机用户名和密码(generatePasswd.sh)
	generate_random_user_and_pwd
	
	# 5.设置同步目录属性
	set_sync_folder
	
	# 6.写入WebDAV配置信息
	write_webdav_config
	
	# 7.生成 webdav-go 的yml配置文件
	set_webdav_go_yml_file
	
	# 8.启动 webdav-go
	start_webdav_go
	
	# 9.关闭防火墙(linux.sh)
	stop_firewall
	
	#10.显示WebDAV配置信息
	display_webdav_config
		
	#11.下载根证书(generateCert.sh)
	download_root_cert
	
	
	
	
	
	
	
}


function uninstall_webdavGo(){

	echo "确定要 卸载nginx及其webdav？[y/n]" && echo
	read -e -p "(默认: n):" uninstall_unyn

	[[ -z ${uninstall_unyn} ]] && uninstall_unyn="n"
	if [[ ${uninstall_unyn} == [Yy] ]]; then
		
		stop_webdav_go

		#删除 webdav-go目录
		rm -rf ${webdav_go_folder}
		
		echo && echo "卸载webdav-nginx完成！" && echo
		
	else
		echo && echo " 已取消卸载..." && echo
	fi

}




# 查看webdav-go日志
function view_webdav_webdav_go_log(){

	# 查看最后20行
	tail -20f ${webdav_go_log}


}







